# -*- coding: utf-8 -*-
# !/usr/bin/env python
from rest_framework.views import APIView

from components.deploy.k8s_release.dao import get_all_kubernetes_cluster_host
from components.kubernetes.api_file_verify import get_info
from components.kubernetes.dao import get_config_file_text
from components.kubernetes.node.dao import save_kubernete_node_info
from utils.K8S import K8sApi
from utils.views import Result, ReturnClass

class VerifyNodeInfo(APIView):
    """
    校对K8S角色信息，对非平台部署的主机查询信息入库
    """
    def put(self, request):
        data = request.data
        kubernetes_cluster_id = data['kubernetes_cluster_id']

        cluster_info = get_info(kubernetes_cluster_id)
        if ReturnClass.if_ok(cluster_info):
            kubernetes_cluster_sign_kubeconfig = ReturnClass.get_value(cluster_info)
        else:
            return Result.fail_response(ReturnClass.get_value(cluster_info))

        k8s_api = K8sApi(kubernetes_cluster_sign_kubeconfig)

        return_data = k8s_api.list_node()

        hots_save_info = get_all_kubernetes_cluster_host(kubernetes_cluster_id)
        for hots_save_info_one in hots_save_info:
            if hots_save_info_one['host_id'] in data['host_ids']:
                for return_data_one in return_data:
                    if return_data_one['InternalIP'] == hots_save_info_one['host_ip']:
                        if return_data_one['labels'].get('node-role.kubernetes.io/master') != None:
                            kubernetes_role = 'master'
                        else:
                            kubernetes_role = 'node'

                        save_kubernete_node_info(hots_save_info_one['host_id'], hots_save_info_one['kubernetes_manage_id'], kubernetes_role, return_data_one['Hostname'])

        return Result.success_response(data=return_data, msg='执行完成')